package org.dromara.canteen.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.school.domain.Campus;
import org.dromara.school.domain.Classes;
import org.dromara.school.domain.bo.ClassesBo;
import org.dromara.school.domain.vo.ClassesVo;
import org.dromara.system.domain.SysuserBindingSchools;
import org.dromara.system.service.ISysuserBindingSchoolsService;
import org.glassfish.jaxb.runtime.v2.runtime.output.SAXOutput;
import org.springframework.stereotype.Service;
import org.dromara.canteen.domain.bo.CanteenFoodBo;
import org.dromara.canteen.domain.vo.CanteenFoodVo;
import org.dromara.canteen.domain.CanteenFood;
import org.dromara.canteen.mapper.CanteenFoodMapper;
import org.dromara.canteen.service.ICanteenFoodService;
import com.github.yulichang.base.MPJBaseServiceImpl;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 食材管理Service业务层处理
 *
 * @author Gjb
 * @date 2025-07-28
 */
@RequiredArgsConstructor
@Service
public class CanteenFoodServiceImpl  extends MPJBaseServiceImpl<CanteenFoodMapper,CanteenFood> implements ICanteenFoodService {

    private final CanteenFoodMapper baseMapper;
    private final ISysuserBindingSchoolsService bindingSchoolsService;
    /**
     * 查询食材管理
     */
    @Override
    public CanteenFoodVo queryById(Long foodId){
        return baseMapper.selectVoById(foodId);
    }

    /**
     * 查询食材管理列表
     */
    @Override
    public TableDataInfo<CanteenFoodVo> queryPageList(CanteenFoodBo bo, PageQuery pageQuery) {
        TenantHelper.clearDynamic();
        MPJLambdaWrapper<CanteenFood> mpj = JoinWrappers.lambda(CanteenFood.class)
            .selectAll(CanteenFood.class)
            .selectAs(Campus::getCampusName, CanteenFoodVo::getSchoolCampusName)
            .leftJoin(Campus.class, Campus::getCampusId, CanteenFood::getSchoolCampusId)
            .logicDelToOn()
            .orderByDesc(CanteenFood::getPurchaseDate);
        if (bo.getSchoolCampusId() != null) {
            mpj.eq(CanteenFood::getSchoolCampusId, bo.getSchoolCampusId());
        }
        if(bo.getPurchaseDate()!=null){
            mpj.eq(CanteenFood::getPurchaseDate,bo.getPurchaseDate());
        }

        if(bo.getCheckOperator()!=null){
            mpj.eq(CanteenFood::getCheckOperator, bo.getCheckOperator());
        }

        LoginUser loginUser = LoginHelper.getLoginUser();
        UserType userType = UserType.getUserType(loginUser.getUserType());
        if(bo.getTenantId()!=null){
            mpj.eq(Campus::getTenantId,bo.getTenantId());
        }

        List<SysuserBindingSchools> bindingSchools = null;
        switch (userType) {
            case SYS_USER:
                TenantHelper.enableIgnore();//忽略默认添加的租户  这样系统账户能看到其他租户的东西
                break;
            case SCHOOLADMIN:

//                List<Integer> campusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
//                mpj.in(Classes::getSchoolCampusId, campusids);
                break;
//            case TEACHER:
////                List<Integer> campusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
////                mpj.in(Classes::getSchoolCampusId, campusids);
//                break;
            case TEACHER:

                bindingSchools = this.bindingSchoolsService.findByUserId(loginUser.getUserId());
                List<Long> teachercampusids = bindingSchools.stream()
                    .map(SysuserBindingSchools::getSchoolCampusId)
                    .collect(Collectors.toList());

                mpj.in(CanteenFood::getSchoolCampusId,teachercampusids);
                break;
            default:
                return null;
        }


        IPage<CanteenFoodVo> ipage = baseMapper.selectJoinPage(
            new Page<CanteenFoodVo>(pageQuery.getPageNum(), pageQuery.getPageSize()),
            CanteenFoodVo.class, mpj
        );



        TableDataInfo<CanteenFoodVo> foodResult = TableDataInfo.build(ipage);


        return foodResult;





//        LambdaQueryWrapper<CanteenFood> lqw = buildQueryWrapper(bo);
//        Page<CanteenFoodVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
    }

    /**
     * 查询食材管理列表
     */
    @Override
    public List<CanteenFoodVo> queryList(CanteenFoodBo bo) {
        LambdaQueryWrapper<CanteenFood> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CanteenFood> buildQueryWrapper(CanteenFoodBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CanteenFood> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getFoodName()), CanteenFood::getFoodName, bo.getFoodName());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), CanteenFood::getUnit, bo.getUnit());
        lqw.eq(bo.getPurchaseDate() != null, CanteenFood::getPurchaseDate, bo.getPurchaseDate());
        lqw.eq(bo.getPrePurchaseQuantity() != null, CanteenFood::getPrePurchaseQuantity, bo.getPrePurchaseQuantity());
        lqw.eq(bo.getPurchaseNetWeight() != null, CanteenFood::getPurchaseNetWeight, bo.getPurchaseNetWeight());
        lqw.eq(bo.getPurchaseGrossWeight() != null, CanteenFood::getPurchaseGrossWeight, bo.getPurchaseGrossWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckOperator()), CanteenFood::getCheckOperator, bo.getCheckOperator());
        lqw.eq(bo.getSchoolCampusId() != null, CanteenFood::getSchoolCampusId, bo.getSchoolCampusId());
        return lqw;
    }

    /**
     * 新增食材管理
     */
    @Override
    public Boolean insertByBo(CanteenFoodBo bo) {
        CanteenFood add = MapstructUtils.convert(bo, CanteenFood.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setFoodId(add.getFoodId());
        }
        return flag;
    }

    /**
     * 修改食材管理
     */
    @Override
    public Boolean updateByBo(CanteenFoodBo bo) {
        CanteenFood update = MapstructUtils.convert(bo, CanteenFood.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CanteenFood entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除食材管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    /**
     * 根据 日期 食材名称 食材重量 学校id 来判断是否存在重复的食材
     */
    public CanteenFood findFood(CanteenFoodVo canteenFoodVo) {

    LambdaQueryWrapper<CanteenFood> queryWrapper = new LambdaQueryWrapper<>();
    if(canteenFoodVo!=null){
        queryWrapper.eq(StringUtils.isNotEmpty(canteenFoodVo.getFoodName()),CanteenFood::getFoodName,canteenFoodVo.getFoodName());
        queryWrapper.eq(canteenFoodVo.getPurchaseDate()!=null,CanteenFood::getPurchaseDate,canteenFoodVo.getPurchaseDate());
        queryWrapper.eq(StringUtils.isNotEmpty(canteenFoodVo.getPrePurchaseQuantity()),CanteenFood::getPrePurchaseQuantity,canteenFoodVo.getPrePurchaseQuantity());
        queryWrapper.eq(CanteenFood::getSchoolCampusId,canteenFoodVo.getSchoolCampusId());
    }
        return this.baseMapper.selectOne(queryWrapper);
    }
}
